<template>
	<view class="container">
		<!-- 顶部用户信息 -->
		<view class="header">
			<view class="user-info">
				<view class="user-profile">
					<image class="avatar" @click="selectImage" :src="User.avatarPath" mode="aspectFill"></image>
					<view class="user-details">
						<view class="username font-title" @click="clicklogin">{{User.name}}</view>
						<view class="user-id font-description">泡泡号：{{User.account}}</view>
					</view>
				</view>
			</view>

			<!-- 用户数据统计 -->
			<view class="stats-card">
				<view class="stats-item" @click="navToStatistics('luckyValue')">
					<text class="stats-value font-bold">{{User.luckyValue}}</text>
					<text class="stats-label color-gray font-description">幸运值</text>
				</view>
				<view class="stats-item" @click="navToStatistics('functionCard')">
					<text class="stats-value font-bold">{{User.functionCardCount}}</text>
					<text class="stats-label color-gray font-description">功能卡</text>
				</view>
				<view class="stats-item" @click="navToStatistics('coupon')">
					<text class="stats-value font-bold">{{User.couponCount}}</text>
					<text class="stats-label color-gray font-description">优惠券</text>
				</view>
				<view class="stats-item" @click="navToStatistics('newShareCoupon')">
					<text class="stats-value font-bold">{{User.newShareCouponCount}}</text>
					<text class="stats-label color-gray font-description">新享券</text>
				</view>
			</view>
		</view>

		<!-- 我的盒柜 -->
		<view class="section box-section">
			<view class="section-header">
				<view class="section-title" @click="navtomyBox()">
					<text class="font-bold">我的盒柜</text>
					<text class="view-all color-gray font-description">全部 ></text>
				</view>
			</view>

			<view class="function-grid">
				<view class="function-item" @click="navToBoxStatus('pending_payment')">
					<image class="function-icon" src="../../static/my/待付款.png" mode=""></image>
					<text class="function-text color-gray font-description">待付款</text>
				</view>
				<view class="function-item" @click="navToBoxStatus('pending_shipment')">
					<image class="function-icon" src="../../static/my/待发货.png" mode=""></image>
					<text class="function-text color-gray font-description">待发货</text>
				</view>
				<view class="function-item" @click="navToBoxStatus('pending_receipt')">
					<image class="function-icon" src="../../static/my/待收货.png" mode=""></image>
					<text class="function-text color-gray font-description">待收货</text>
				</view>
				<view class="function-item" @click="navToBoxStatus('completed')">
					<image class="function-icon" src="../../static/my/已完成.png" mode=""></image>
					<text class="function-text color-gray font-description">已完成</text>
				</view>
			</view>

			<!-- 轮播广告 -->
			<view class="carousel">
				<swiper class="swiper" :autoplay="true" :interval="3000" :duration="1000" circular>
					<swiper-item v-for="(image, index) in ['宣传图片1.jpeg', '宣传图片2.jpeg', '宣传图片3.jpeg', '宣传图片4.jpeg']" :key="index">
						<image class="swiper-image" :src="`../../static/my/${image}`" mode="aspectFill"></image>
					</swiper-item>
				</swiper>
			</view>
		</view>

		<!-- 泡泡服务 -->
		<view class="section service-section">
			<view class="section-header">
				<text class="section-title font-bold">我的服务</text>
			</view>

			<view class="service-list">
				<view v-for="(item,index) in service" :key="index" class="service-item" @click="selectservice(index)">
					<text class="service-name">{{item.name}}</text>
					<image class="arrow-icon" src="../../static/my/箭头.png"></image>
				</view>
			</view>

			<van-button plain round type="primary" size="large" class="logout-btn" @click="clickloginout">
				退出登录
			</van-button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		onUnmounted,
		defineExpose
	} from 'vue';

	// 响应式数据
	const User = reactive({
		avatarPath: '',
		name: '请登录',
		account: 'xxxxxxxxxxxxxx',
		luckyValue: 200,
		functionCardCount: 3,
		couponCount: 2,
		newShareCouponCount: 1,
		status: 0
	});

	const service = ref([{
			id: 1,
			name: '收货地址',
			url: '/pages/addressDelivery/addressDelivery'
		},
		{
			id: 2,
			name: '我的心愿',
			url: '/pages/index/index'
		},
		{
			id: 3,
			name: '联系客服',
			url: '/pages/customerService/customerService'
		},
		{
			id: 4,
			name: '抽盒记录',
			url: '/pages/index/index'
		},
		{
			id: 5,
			name: '试试手气',
			url: '/pages/index/index'
		},
		{
			id: 6,
			name: '展会',
			url: '/pages/homepage/homepage'
		},
		{
			id: 7,
			name: '设置',
			url: '/pages/setting/setting'
		},
	]);

	// 刷新用户信息
	const refreshUserInfo = () => {
		console.log('刷新用户信息被调用');
		loadUserInfo();
	};

	// 加载用户信息
	const loadUserInfo = () => {
		console.log('加载用户信息');
		
		const loadTasks = [
			// 获取用户账号
			new Promise((resolve) => {
				uni.getStorage({
					key: 'userName',
					success: function(res) {
						User.account = res.data;
						resolve();
					},
					fail: function(err) {
						console.error('获取用户账号失败', err);
						resolve();
					}
				});
			}),
			
			// 获取用户姓名
			new Promise((resolve) => {
				uni.getStorage({
					key: 'nickName',
					success: function(res) {
						User.name = res.data;
						resolve();
					},
					fail: function(err) {
						console.error('获取用户昵称失败', err);
						resolve();
					}
				});
			}),
			
			// 获取用户头像
			new Promise((resolve) => {
				uni.getStorage({
					key: 'userImg',
					success: function(res) {
						User.avatarPath = res.data;
						resolve();
					},
					fail: function(err) {
						console.error('获取用户头像失败', err);
						resolve();
					}
				});
			}),
			
			// 获取用户状态
			new Promise((resolve) => {
				uni.getStorage({
					key: 'userstatus',
					success: function(res) {
						User.status = res.data;
						resolve();
					},
					fail: function(err) {
						console.error('获取用户状态失败', err);
						resolve();
					}
				});
			})
		];
		
		// 等待所有数据加载完成
		Promise.all(loadTasks).then(() => {
			console.log('数据加载完成', User);
		});
	};

	// 页面显示时检查存储
	const checkStorage = () => {
		console.log('检查存储');
		// 刷新数据
		loadUserInfo();
		
		// 检查是否有强制刷新标志
		uni.getStorage({
			key: 'forceRefresh',
			success: (res) => {
				if (res.data === true) {
					console.log('检测到forceRefresh标志，清除');
					// 清除标志
					uni.setStorageSync('forceRefresh', false);
				}
			}
		});
	};
	
	// 检查登录状态并导航的通用函数
	const checkLoginAndNavigate = (url) => {
		// 检查用户是否已登录
		if (User.status == 0) {
			// 用户未登录，显示提示并引导至登录页面
			uni.showModal({
				title: '提示',
				content: '请先登录后再使用此功能',
				confirmText: '去登录',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/pages/login/login'
						});
					}
				}
			});
			return false;
		}
		
		// 用户已登录，正常跳转
		uni.navigateTo({
			url: url
		});
		return true;
	};

	// 方法
	const selectImage = () => {
		// 检查用户是否已登录
		if (User.status == 0) {
			// 用户未登录，显示提示并引导至登录页面
			uni.showModal({
				title: '提示',
				content: '请先登录后再更改头像',
				confirmText: '去登录',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/pages/login/login'
						});
					}
				}
			});
			return;
		}
		
		// 用户已登录，正常选择图片
		uni.chooseImage({
			count: 1,
			success: (res) => {
				// 更新头像
				User.avatarPath = res.tempFilePaths[0];
			}
		});
	};

	const clicklogin = () => {
		if (User.status == 0) {
			uni.reLaunch({
				url: '/pages/login/login'
			});
		}
	};

	const clickloginout = () => {
		// 调用退出登录API
		uni.clearStorage()
		User.name = "请登录"
		User.account = "xxxxxxxxxxxxxx"
		User.status = 0
		
		// 跳转到登录页
		uni.showToast({
			title: '退出成功',
			success: () => {
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/login/login'
					});
				}, 1500);
			}
		});
	};

	const selectservice = (index) => {
		var item = service.value[index];
		checkLoginAndNavigate(item.url);
	};

	const navtomyBox = () => {
		checkLoginAndNavigate('/pages/myBox/myBox');
	};

	const navToBoxStatus = (status) => {
		// 将状态字符串映射到状态码
		const statusMap = {
			'pending_payment': 1,  // 待付款
			'pending_shipment': 2, // 待发货
			'pending_receipt': 3,  // 待收货
			'completed': 4         // 已完成
		};
		
		const statusCode = statusMap[status] || 0;
		checkLoginAndNavigate(`/pages/myBox/myBox?status=${statusCode}`);
	};

	const navToStatistics = (type) => {
		// 将统计类型映射到对应页面URL
		const urlMap = {
			'luckyValue': '/pages/lucky/luckyValue',
			'functionCard': '/pages/cards/functionCards',
			'coupon': '/pages/coupons/coupons',
			'newShareCoupon': '/pages/coupons/newShareCoupons'
		};
		
		const url = urlMap[type] || '/pages/index/index';
		checkLoginAndNavigate(url);
	};

	// 页面生命周期
	onMounted(() => {
		console.log('页面加载');
		// 首次加载数据
		loadUserInfo();
		
		// 添加事件监听
		uni.$on('userInfoUpdated', refreshUserInfo);
		uni.$on('refreshUserProfile', refreshUserInfo);
		uni.$on('forceRefreshPages', refreshUserInfo);
		uni.$on('globalRefresh', refreshUserInfo);
	});

	onUnmounted(() => {
		// 清理事件监听
		uni.$off('userInfoUpdated');
		uni.$off('refreshUserProfile');
		uni.$off('forceRefreshPages');
		uni.$off('globalRefresh');
	});

	// 导出方法供页面调用
	defineExpose({
		refreshUserInfo,
		loadUserInfo,
		checkStorage
	});
</script>

<script>
export default {
	// 页面生命周期
	onLoad() {
		// console.log('页面onLoad');
	},
	
	onShow() {
		// console.log('页面onShow');
		// 每次页面显示时刷新数据
		if (this.$vm && typeof this.$vm.checkStorage === 'function') {
			this.$vm.checkStorage();
		}
	}
}
</script>

<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		background-color: #f8f8f8;
		padding-bottom: 40rpx;
	}

	// 通用样式
	.font-bold { font-weight: 600; }
	.font-description { font-size: 24rpx; }
	.font-title { font-size: 36rpx; }
	.color-gray { color: #666; }

	// 头部样式
	.header {
		background: linear-gradient(180deg, #4a90e2, #6eb4f7);
		padding: 40rpx 30rpx;
		color: #fff;

		.user-info {
			margin-bottom: 40rpx;
		}

		.user-profile {
			display: flex;
			align-items: center;
			gap: 20rpx;
		}

		.avatar {
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
			border: 4rpx solid rgba(255,255,255,0.8);
			box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
		}

		.user-details {
			.username {
				margin-bottom: 8rpx;
				color: #fff;
			}
			.user-id {
				opacity: 0.8;
			}
		}
	}

	// 统计卡片
	.stats-card {
		background: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin: -20rpx 20rpx 0;
		display: flex;
		justify-content: space-around;
		box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.08);

		.stats-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			gap: 8rpx;

			.stats-value {
				font-size: 32rpx;
				color: #333;
			}

			.stats-label {
				font-size: 24rpx;
			}
		}
	}

	// 内容区域
	.section {
		background: #fff;
		border-radius: 16rpx;
		margin: 20rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);

		.section-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 30rpx;

			.section-title {
				font-size: 32rpx;
			}

			.view-all {
				opacity: 0.6;
			}
		}
	}

	// 功能网格
	.function-grid {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		gap: 20rpx;
		margin: 30rpx 0;

		.function-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			gap: 12rpx;

			.function-icon {
				width: 80rpx;
				height: 80rpx;
				padding: 16rpx;
				background: #f5f7fa;
				border-radius: 50%;
			}

			.function-text {
				font-size: 24rpx;
			}
		}
	}

	// 轮播图
	.carousel {
		margin: 20rpx 0;
		border-radius: 12rpx;
		overflow: hidden;

		.swiper {
			height: 300rpx;

			.swiper-image {
				width: 100%;
				height: 100%;
				border-radius: 12rpx;
			}
		}
	}

	// 服务列表
	.service-list {
		.service-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 24rpx 0;
			border-bottom: 2rpx solid #f5f5f5;

			&:last-child {
				border-bottom: none;
			}

			.service-name {
				font-size: 28rpx;
				color: #333;
			}

			.arrow-icon {
				width: 32rpx;
				height: 32rpx;
				opacity: 0.6;
			}
		}
	}

	// 退出按钮
	.logout-btn {
		margin-top: 40rpx;
		width: 100% !important;
	}
</style> 